/*
TODO:

- Add command line variable for serial port
- Cycling Routines (think on framework)

*/

//Set it up
var http = require("http"); //HTTP Server
var url = require("url"); // URL Handling
var fs = require('fs'); // Filesystem Access (writing files)
var glob = require('glob'); // Easy directory searches (from python)
var express = require('express'), //App Framework (similar to web.py abstraction)
    app = express.createServer();
	app.use(express.bodyParser());
	app.use(app.router);
	
var exec = require('child_process').exec;
var child1
var child2;

var bname="string0001"

//MongoDB stuff
db_connected = false
try
{
	//var Mongolian = require("mongolian")
	//var server = new Mongolian
	var mongo = require('mongoskin');
	var db = mongo.db("localhost:27017/" + bname)
	db_connected = true
	central_info = "central_info"
	
}
catch (err)
{
	console.log(err)
}


//This is the core call that reads data from Inverter and Metering device, sets the inverters and records last known settings
//The update is done twice per minute (30000)

update_time=30000
setInterval(function() {
	// Go to Python ... everything happens in the py code
	child1 = exec("/usr/bin/python ./databaseWrite.py", function (error, stdout, stderr) {
		console.log(stdout);
		if (error !== null) {
			console.log('Critical Error -- shutdown alert : ' + error);
		} else {
			console.log('Inverter updated okay');
		}
	});		
	},update_time)


//Express Redirects
//Static Redirects
app.use("/flot", express.static(__dirname + '/flot'));

//On Home Page
app.get('/plotter', function(req, res){	
	indexer = fs.readFileSync('plotter.html').toString()
    res.send(indexer);
});

app.get('/realtime*', function(req, res){
	
	indexer = fs.readFileSync('realtime.html').toString()
    res.send(indexer);
});

app.get('/', function(req, res){	
	indexer = fs.readFileSync('realtime.html').toString()
    res.send(indexer);
});

//Accept data (all pages, throws to setStuff()
app.post('/senddata', setStuff,function(req, res,next){
	res.send(req.body)	
});

//Used to get load data
app.post('/getdata',getStuff,function(req, res){
	res.send(req.app.settings)
});

//Used to write control instructions
app.post('/writecontrol',writeControl,function(req, res){
	res.send(req.app.settings)
});

//Used to read control instructions
app.post('/readcontrol',readControl,function(req, res){
	res.send(req.app.settings)
});

//Used to show sensor data
app.post('/getsensor',sensorStuff,function(req, res){
	res.send(req.app.settings)
});

//Start listener on this port
app.listen(80);
console.log('Express server started on port %s', app.address().port);

//Program Functions
function setStuff(req,res)
{
	///req.body.stuff	
}

function writeControl(req,res)
{
	console.log("Write Control")
	//all is off in case there are problems
	var charge_threshold=0;
	var invert_threshold=0;
	var max_charge_current=0;
	var max_sell_current=0;
	var status=0;
	var sell_state=0;
	var charge_state=0;
	if(req.param('charge_threshold', null)!=undefined) charge_threshold=parseInt(req.param('charge_threshold', null))
	if(req.param('invert_threshold', null)!=undefined) invert_threshold=parseInt(req.param('invert_threshold', null))
	if(req.param('max_charge_current', null)!=undefined) max_charge_current=parseInt(req.param('max_charge_current', null))
	if(req.param('max_sell_current', null)!=undefined) max_sell_current=parseInt(req.param('max_sell_current', null))
	if(req.param('charge_state', null)!=undefined) charge_state=parseInt(req.param('charge_state', null))		
	if(req.param('sell_state', null)!=undefined) sell_state=parseInt(req.param('sell_state', null))		
	if(req.param('status', null)!=undefined) status=parseInt(req.param('status', null))		
	if (db_connected) {
		db.collection("control").update({"label" : 0},{"label" :0,  "charge_threshold" : charge_threshold ,"invert_threshold" : invert_threshold ,"max_charge_current" : max_charge_current ,"max_sell_current" : max_sell_current ,"status" :status, "sell_state" : sell_state ,"charge_state" : charge_state}, true);
	}
	//Read controls and send response back to page
	readControl(req,res)
}

//Read control parameters
function readControl(req,res)
{	
	console.log("Read Control")
	var dbreq="{\"collection\":\"control\",\"query\":{},\"fields\":{\"label\":1,\"invert_threshold\":1,\"charge_threshold\":1,\"max_sell_current\":1,\"max_charge_current\":1, \"charge_state\":1 ,\"sell_state\":1 ,\"status\":1}}"
	var foo = JSON.parse(dbreq)
	var collection = foo.collection
	var q = foo.query
	var l = undefined
	var s = {}	
	var f = {}
	if (foo.limit != undefined) l = foo.limit
	if (foo.sort != undefined) s = foo.sort
	if (foo.fields != undefined) f = foo.fields
	if (q == '') q = null
		db.collection(collection).find(q,f).limit(l).sort(s).count(function(err,count)
		{
			db.collection(collection).find(q,f).limit(l).sort(s).toArray(function(err,data)
			{
				res.send({collect:collection,data:data})	
			})			
		})
}

//get last sensor readings
function sensorStuff(req,res)
{
	console.log("Start Sensor: " + req.body.data)
	var foo = JSON.parse(req.body.data)
	var collection = foo.collection
	var q = foo.query
	var l = undefined
	var s = {}	
	var f = {}
	if (foo.limit != undefined) l = foo.limit
	if (foo.sort != undefined) s = foo.sort
	if (foo.fields != undefined) f = foo.fields
	if (q == '') q = null
		db.collection(collection).find(q,f).limit(l).sort(s).count(function(err,count)
		{
			db.collection(collection).find(q,f).limit(l).sort(s).toArray(function(err,data)
			{
				res.send({collect:collection,data:data})	
			})			
		})
	console.log("End Sensor")
}

//Get realtime data for plots
function getStuff(req,res)
{
	console.log("Start Data: " + req.body.data)
	var foo = JSON.parse(req.body.data)
	var collection = foo.collection
	var q = foo.query
	var l = undefined
	var s = {}	
	var f = {}
	if (foo.limit != undefined) l = foo.limit
	if (foo.sort != undefined) s = foo.sort
	if (foo.fields != undefined) f = foo.fields
	if (q == '') q = null
	db.collection(collection).find(q,f).limit(l).sort(s).count(function(err,count)
		{
			max_docsish = 1500
			if (count > max_docsish)
			{
				ranger = Math.floor(parseFloat(count)/parseFloat(max_docsish))
				if (q['time'] == undefined) q['time'] = {}
				q['time']['$mod'] = [ranger,0]
				
			}	
			db.collection(collection).find(q,f).limit(l).sort(s).toArray(function(err,data)
			{
				res.send({collect:collection,data:data})	
			})			
		})
	console.log("End Data")
}